package com.bond.webfluxdemo.controller;

import com.bond.webfluxdemo.entry.City;
import com.bond.webfluxdemo.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Controller
@RequestMapping(value = "/city")
public class CityWebFluxController {

    @Autowired
    private CityService cityService;

    @GetMapping(value = "/{id}")
    @ResponseBody
    public Mono<City> findCityById(@PathVariable("id") Long id) {
        return cityService.findCityById(id);
    }

    @GetMapping()
    @ResponseBody
    public Flux<City> findAllCity() {
        return cityService.findAllCity();
    }

    @PostMapping()
    @ResponseBody
    public Mono<Long> saveCity(@RequestBody City city) {
        return cityService.save(city);
    }

    @PutMapping()
    @ResponseBody
    public Mono<Long> modifyCity(@RequestBody City city) {
        return cityService.modifyCity(city);
    }

    @DeleteMapping(value = "/{id}")
    @ResponseBody
    public Mono<Long> deleteCity(@PathVariable("id") Long id) {
        return cityService.deleteCity(id);
    }







    // 页面响应 ##############################################

    @GetMapping("/websocket")
    public Mono<String> websocket() {
        return Mono.create(monoSink -> monoSink.success("websocket"));
    }

    @GetMapping("/hello")
    public Mono<String> hello(final Model model) {
        model.addAttribute("name", "泥瓦匠");
        model.addAttribute("city", "浙江温岭");

        String path = "hello";
        return Mono.create(monoSink -> monoSink.success(path));
    }


    @GetMapping("/page/list")
    public String listPage(final Model model) {

        //如果有大于0条的数据，浏览器请求一次，数据会按指定的秒数向前端推送一条数据。
//        // 以数据驱动模式，数据流，每两秒传给前端一条数据
//        final Flux<City> cityFluxList = cityHandler.findAllCity().delayElements(Duration.ofSeconds(2));
//        // 加载一个，显示一个 loads 1 and display 1, stream data, data driven mode.
//        IReactiveDataDriverContextVariable reactiveDataDrivenMode =
//                new ReactiveDataDriverContextVariable(cityFluxList, 1);
//        model.addAttribute("cityList", reactiveDataDrivenMode);

        //普通模式
        final Flux<City> cityFluxList = cityService.findAllCity();
        model.addAttribute("cityList", cityFluxList);

        return "cityList";
    }

}
